// 引入配置文件
const kindergartenQuestions = require('./kindergartenQuestions.js');
const primaryQuestions = require('./primaryQuestions.js');
const juniorQuestions = require('./juniorQuestions.js');
const seniorQuestions = require('./seniorQuestions.js');
const app = getApp();
let rewardedVideoAd = null;
let interAd = null;
Page({
  data: {
    score: '新手玩家',
    numbers: [],
    selectedNumberIndex: null,
    operator: null,
    firstSelected: false,
    originalLevel: 'kindergarten',
    originalIndex: 0,
    resultTip: '',
    resultTipClass: '',
    isSuccess: false,
    solutions: []
  },
  onLoad: function (options) {
    const level = options.level;
    const questions = this.getQuestionsByLevel(level);
    const randomIndex = Math.floor(Math.random() * questions.length);
    const originalNumbers = questions[randomIndex].split(',');
    console.log('初始数值', originalNumbers);
    this.setData({
      numbers: originalNumbers,
      originalLevel: level,
      originalIndex: randomIndex,
      showSolutions: [],
      score: app.globalData.score
    });
    this.LoadAd();
  },
  getQuestionsByLevel: function (level) {
    switch (level) {
      case "kindergarten":
        return kindergartenQuestions;
      case "primary":
        return primaryQuestions;
      case "junior":
        return juniorQuestions;
      case "senior":
        return seniorQuestions;
      default:
        return [];
    }
  },
  selectNumber: function (e) {
    app.playSound('enniu');
    const index = e.currentTarget.dataset.index;
    console.log('选中', index);
    if (!this.data.firstSelected) {
      this.setData({
        selectedNumberIndex: index,
        firstSelected: true
      });
    } else if (this.data.operator) {
      this.performCalculation(index);
    } else {
      this.setData({
        selectedNumberIndex: index
      });
    }
  },
  performOperation: function (e) {
    app.playSound('enniu');
    const operator = e.currentTarget.dataset.operator;
    this.setData({
      operator: operator
    });
  },
  performCalculation: function (secondIndex) {
    const numbers = this.data.numbers;
    const firstIndex = this.data.selectedNumberIndex;
    const operator = this.data.operator;
    let result;
    switch (operator) {
      case "+":
        result = parseFloat(numbers[firstIndex]) + parseFloat(numbers[secondIndex]);
        break;
      case "-":
        result = parseFloat(numbers[firstIndex]) - parseFloat(numbers[secondIndex]);
        break;
      case "*":
        result = parseFloat(numbers[firstIndex]) * parseFloat(numbers[secondIndex]);
        break;
      case "/":
        result = parseFloat(numbers[firstIndex]) / parseFloat(numbers[secondIndex]);
        break;
    }
    numbers.splice(Math.min(firstIndex, secondIndex), 1);
    numbers.splice(Math.max(firstIndex, secondIndex) - 1, 1, result.toString());
    this.setData({
      numbers: numbers,
      selectedNumberIndex: null,
      operator: null,
      firstSelected: false
    });

    let resultTip = '';
    let resultTipClass = '';
    let isSuccess = false;
    if (numbers.length === 1 && parseFloat(numbers[0]) === 24) {
      app.playSound('upgrade');
      resultTip = '恭喜成功！';
      resultTipClass = 'success-tip';
      isSuccess = true;
      this.addScore();
      if (interAd) interAd.show();
    } else if (numbers.length === 1 && parseFloat(numbers[0]) !== 24) {
      resultTip = '不对哦！';
      resultTipClass = 'error-tip';
    }

    this.setData({
      numbers: numbers,
      selectedNumberIndex: null,
      operator: null,
      firstSelected: false,
      resultTip: resultTip,
      resultTipClass: resultTipClass,
      isSuccess: isSuccess
    });
  },
  resetGame: function () {
    const questions = this.getQuestionsByLevel(this.data.originalLevel);
    const randomIndex = this.data.originalIndex;
    const originalNumbers = questions[randomIndex].split(',');
    this.setData({
      numbers: originalNumbers,
      selectedNumberIndex: null,
      operator: null,
      firstSelected: false,
      resultTip: '',
      resultTipClass: '',
      isSuccess: false,
      solutions: []
    });
  },
  nextQuestion: function () {
    app.playSound('next');
    const questions = this.getQuestionsByLevel(this.data.originalLevel);
    const randomIndex = Math.floor(Math.random() * 100);
    this.setData({
      numbers: questions[randomIndex].split(','),
      originalIndex: randomIndex,
      selectedNumberIndex: null,
      operator: null,
      firstSelected: false,
      resultTip: '',
      resultTipClass: '',
      isSuccess: false,
      solutions: []
    });
  },
  //增加积分
  addScore: function () {
    // 假设用户答对了题目，根据难度增加积分
    const level = this.data.originalLevel;
    let scoreIncrement = 0;
    switch (level) {
      case "kindergarten":
        scoreIncrement = 1;
        break;
      case "primary":
        scoreIncrement = 2;
        break;
      case "junior":
        scoreIncrement = 3;
        break;
      case "senior":
        scoreIncrement = 4;
        break;
    }
    app.globalData.score += scoreIncrement;
    wx.setStorageSync('score', app.globalData.score);

    this.setData({
      score: app.globalData.score
    });
    // 检查称号是否升级
    const isUpgraded = app.checkTitleUpgrade();
    if (isUpgraded) {
      wx.showToast({
        title: `恭喜！您已升级为 ${app.globalData.title}！`,
      })
    }
  },
  showTip: function () {
    if (rewardedVideoAd) {
      console.log("show ad");
      rewardedVideoAd.show();
    } else
      this.showSolutions();
  },
  // 显示提示信息
  showSolutions: function () {
    this.resetGame();
    const numbers = this.data.numbers.map(Number);
    //console.log('提示', numbers);
    const solutions = this.find24(numbers);
    //console.log('提示2', solutions);
    this.setData({
      solutions: solutions
    });
  },
  // 求解 24 点问题
  find24: function (nums) {
    if (nums.length !== 4) {
      return ["请输入4个数字"];
    }

    const allSolutions = [];

    // 递归函数，尝试所有可能的运算组合
    function dfs(nums, path) {
      if (nums.length === 1) {
        if (Math.abs(nums[0] - 24) < 1e-6) {
          allSolutions.push(path[0]);
          return;
        }
        return;
      }

      for (let i = 0; i < nums.length; i++) {
        for (let j = 0; j < nums.length; j++) {
          if (i === j) continue;

          const nextNums = [];
          const nextPath = [];
          for (let k = 0; k < nums.length; k++) {
            if (k !== i && k !== j) {
              nextNums.push(nums[k]);
              nextPath.push(path[k]);
            }
          }

          // 尝试加法
          const addResult = nums[i] + nums[j];
          const addPath = `(${path[i]} + ${path[j]})`;
          nextNums.push(addResult);
          nextPath.push(addPath);
          dfs(nextNums, nextPath);
          nextNums.pop();
          nextPath.pop();

          // 尝试减法
          const subResult = nums[i] - nums[j];
          const subPath = `(${path[i]} - ${path[j]})`;
          nextNums.push(subResult);
          nextPath.push(subPath);
          dfs(nextNums, nextPath);
          nextNums.pop();
          nextPath.pop();

          // 尝试乘法
          const mulResult = nums[i] * nums[j];
          const mulPath = `(${path[i]} * ${path[j]})`;
          nextNums.push(mulResult);
          nextPath.push(mulPath);
          dfs(nextNums, nextPath);
          nextNums.pop();
          nextPath.pop();

          // 尝试除法
          if (nums[j] !== 0) {
            const divResult = nums[i] / nums[j];
            const divPath = `(${path[i]} / ${path[j]})`;
            nextNums.push(divResult);
            nextPath.push(divPath);
            dfs(nextNums, nextPath);
            nextNums.pop();
            nextPath.pop();
          }
        }
      }
    }

    const path = nums.map(num => num.toString());
    dfs(nums, path);

    return allSolutions;
  },
  LoadAd: function(){
    if (wx.createInterstitialAd && !interAd) {
      interAd = wx.createInterstitialAd({
        adUnitId: 'adunit-298337366f8056a3'
      })
      interAd.onLoad(() => {
        console.log('interstitialAd onLoad event emit')
      })
      interAd.onError((err) => {
        console.log('interstitialAd onError event emit', err)
      })
      interAd.onClose((res) => {
        console.log('interstitialAd onClose event emit', res)
      })
    }

    if (wx.createRewardedVideoAd && !rewardedVideoAd) {
      rewardedVideoAd = wx.createRewardedVideoAd({
        adUnitId: 'adunit-bb0a6e83898021de'
      })
      rewardedVideoAd.onLoad(() => {
        console.log('rewardedVideoAd onLoad event emit')
      })
      rewardedVideoAd.onError((err) => {
        console.log('rewardedVideoAd onError event emit', err)
        this.showSolutions();
      })
      rewardedVideoAd.onClose((status) => {
        if (status && status.isEnded || status === undefined) {
          console.log('rewardedVideoAd 正常播放结束，下发奖励', status)
          // 正常播放结束，下发奖励
          this.showSolutions();
        } else {
          console.log('rewardedVideoAd 播放中途退出，进行提示', status)
          // 播放中途退出，进行提示
          wx.showToast({
            title: '请播放完毕',
          })
        }
      })
    }
  }

});